package com.lintf.web.controller.musicPlayer;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.lintf.common.annotation.Anonymous;
import com.lintf.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @ system:Mac
 * @ author:lin tingfeng
 * @ data:2023/12/19 09:35
 * @ package_name:com.lintf.web.controller.musicPlayer
 * @ project_name:mobile-project
 * @ desc:
 */
@Slf4j
@Anonymous
@RestController
public class MusicPlayerController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${music.url}")
    private String url;

    private Map<String, JSONObject> cachedDataMap = new HashMap<>(); // 暂存的数据

    private static final String[] API_PATHS = {
            "/toplist/detail",
            "/playlist/detail",
            "/search/hot/detail"
    };

    private void fetchDataFromThirdParty(String apiPath) {
//        log.info("Fetching data from third-party API for {}", apiPath);
        String temp;
        StringBuilder sb;
        JSONArray songIds = new JSONArray();
        switch (apiPath) {
            case "/playlist/detail":
                JSONObject topListDetail = cachedDataMap.get("/toplist/detail");
                JSONArray list = topListDetail.getJSONArray("list");
                for (int i = 0; i < Math.min(4, list.size()); i++) {
                    temp = apiPath;
                    // 获取每个元素的 JSONObject
                    JSONObject element = list.getJSONObject(i);
                    temp = temp + "?id=" + element.getString("id");
                    sb = new StringBuilder().append(url).append(temp);
                    JSONObject result = restTemplate.getForObject(sb.toString(), JSONObject.class);
                    if (result != null) {
                        cachedDataMap.put(temp, result);
//                        log.info("Fetched data for {}: {}", temp, result);
                        JSONArray privileges = result.getJSONArray("privileges");
                        for (int j = 0; j < privileges.size(); j++) {
                            JSONObject jsonObject = privileges.getJSONObject(j);
                            songIds.add(String.valueOf(jsonObject.get("id")));
                        }
                    }
                }
                JSONObject songDetail = new JSONObject();
                songDetail.put("songIds", songIds);
                cachedDataMap.put("/song/detail", songDetail);
                break;
            case "/toplist/detail":
            case "/search/hot/detail":
                sb = new StringBuilder().append(url).append(apiPath);
                JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
                if (object != null) {
                    cachedDataMap.put(apiPath, object);
//                    log.info("Fetched data for {}: {}", apiPath, object);
                }
                break;
            case "/song/detail":
                JSONObject jsonObject = cachedDataMap.get(apiPath);
                JSONArray ids = jsonObject.getJSONArray("songIds");
                for (int i = 0; i < ids.size(); i++) {
                    temp = apiPath;
                    // 获取每个元素的 JSONObject
                    temp = temp + "?ids=" + ids.getString(i);
                    sb = new StringBuilder().append(url).append(temp);
                    JSONObject result = restTemplate.getForObject(sb.toString(), JSONObject.class);
                    if (result != null) {
                        cachedDataMap.put(temp, result);
//                        log.info("Fetched data for {}: {}", temp, result);
                    }
                }
                break;
        }
    }

    // 启动定时任务，在应用启动时执行
    @PostConstruct
    private void startScheduledTask() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        for (String apiPath : API_PATHS) {
            scheduler.scheduleAtFixedRate(() -> fetchDataFromThirdParty(apiPath), 0, 1, TimeUnit.HOURS);
        }
    }

    @GetMapping("/toplist/detail")
    public AjaxResult topList() {
        JSONObject object;
        if (cachedDataMap.containsKey("/toplist/detail")) {
            log.info("===获取缓存数据成功===");
            object = cachedDataMap.get("/toplist/detail");
        } else {
            log.info("===获取缓存数据失败===");
            log.info("===开始获取三方接口数据===");
            StringBuilder sb = new StringBuilder().append(url).append("/toplist/detail");
            object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        }
        return AjaxResult.success(object);
    }

    @GetMapping("/playlist/detail")
    public AjaxResult playlistByDetail(Integer id) {
        JSONObject object;
        String path = "/playlist/detail?id=" + id;
        if (cachedDataMap.containsKey(path)) {
            log.info("===获取缓存数据成功===");
            object = cachedDataMap.get(path);
        } else {
            log.info("===获取缓存数据失败===");
            log.info("===开始获取三方接口数据===");
            StringBuilder sb = new StringBuilder().append(url).append("/playlist/detail?id=").append(id);
            object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        }
        return AjaxResult.success(object);
    }

    @GetMapping("/song/detail")
    public AjaxResult songDetail(Integer ids) {
        String path = "/song/detail?ids=" + ids;
        JSONObject object;
        if (cachedDataMap.containsKey(path)) {
            log.info("===获取缓存数据成功===");
            object = cachedDataMap.get(path);
        } else {
            log.info("===获取缓存数据失败===");
            log.info("===开始获取三方接口数据===");
            StringBuilder sb = new StringBuilder().append(url).append("/song/detail?ids=").append(ids);
            object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        }
        return AjaxResult.success(object);
    }

    @GetMapping("/song/url")
    public AjaxResult songUrl(Integer id) {
        StringBuilder sb = new StringBuilder().append(url).append("/song/url?id=").append(id);
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

    @GetMapping("/song/lyric")
    public AjaxResult songLyric(Integer id) {
        StringBuilder sb = new StringBuilder().append(url).append("/lyric?id=").append(id);
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

    @GetMapping("/simi/song")
    public AjaxResult songSimi(Integer id) {
        StringBuilder sb = new StringBuilder().append(url).append("/simi/song?id=").append(id);
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

    @GetMapping("/comment/music")
    public AjaxResult songComment(Integer id) {
        StringBuilder sb = new StringBuilder().append(url).append("/comment/music?id=").append(id);
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

    @GetMapping("/search/hot/detail")
    public AjaxResult searchHot() {
        JSONObject object;
        if (cachedDataMap.containsKey("/search/hot/detail")) {
            log.info("===获取缓存数据成功===");
            object = cachedDataMap.get("/search/hot/detail");
        } else {
            log.info("===获取缓存数据失败===");
            log.info("===开始获取三方接口数据===");
            StringBuilder sb = new StringBuilder().append(url).append("/search/hot/detail");
            object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        }
        return AjaxResult.success(object);
    }

    @GetMapping("/search")
    public AjaxResult searchWord(String keywords) {
        StringBuilder sb = new StringBuilder().append(url).append("/search?keywords=").append(keywords);
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

    @GetMapping("/search/suggest")
    public AjaxResult searchSuggest(String keywords) {
        StringBuilder sb = new StringBuilder().append(url).append("/search/suggest?keywords=").append(keywords).append("&type=mobile");
        JSONObject object = restTemplate.getForObject(sb.toString(), JSONObject.class);
        return AjaxResult.success(object);
    }

}
